import Vue from 'vue' 
import vuex from 'vuex' 
Vue.use(vuex);
//状态
const state ={
    flag:'flag',
    count:1,
    isShowNav:true,
    addCartDatas:[]
};
//计算属性
var  getters ={
    count(state){
        return state.count
    },
    shownav(state){
        return state.isShowNav
    },
    cartDatas(state){
        return state.addCartDatas
    },
    total(state){
        //reduce()计算数组元素相加后的总和
        //累加器  money计算返回值   item当前元素  0传递给函数的初始值
        return state.addCartDatas.reduce(function(money, item){
            return money + item.product_uprice * item.goods_num
        }, 0);
    },
};
//管理mutations
const actions = {
    abc:({commit,state})=>{
        commit('abc')
    },
    add:({commit,state})=>{
        commit('add')
    },
    del:({commit,state})=>{
        if(state.count >2){
            commit('del')
        }
    },
    hideNav:({commit,state})=>{
        commit('hideNav')
    },
    showNav:({commit,state})=>{
        commit('showNav')
    },
    cartAdd:({commit,state},data)=>{
        commit('cartAdd',data)
    },
    //添加数量
    goodIncrement:({commit,state},product_id)=>{
        state.addCartDatas.filter(function(item){return item.product_id == product_id})[0].goods_num++
    },
    //减少数量
    goodDecrement:({commit,state},product_id)=>{
      let num2 = state.addCartDatas.filter(function(item){return item.product_id == product_id})[0];
      if(num2 && num2.goods_num>0){
          num2.goods_num--
      }
    },
    //删除数据
    delCartDatas({commit, state}, product_id) {
        console.log(product_id);
        for(let i=0;i<state.addCartDatas.length;i++){
            if(state.addCartDatas[i].product_id == product_id){
                state.addCartDatas.splice(i,1);
                break;
            }
        }
        
    },
}
//改变状态
const mutations = {
    abc:(state) => {
        state.flag='mutations'
    },
    add:(state) => {
        state.count++;
    },
    del:(state) => {
        state.count--;
    },
    hideNav:(state) => {
        state.isShowNav = false;
    },
    showNav:(state) => {
        state.isShowNav = true;
    },
    //添加购物车
    cartAdd:(state,data)=>{
        //state.addCartDatas.push(data);
        if(state.addCartDatas.length>0){
            let item = state.addCartDatas.filter(function(item){return item.product_id == data.product_id})[0];
            if(item){
                item.goods_num++
            }else {
                state.addCartDatas.push(data);
            }
        }else {
            state.addCartDatas.push(data);
        }
    }
};
const store = new vuex.Store({
  state,
  getters,
  actions,
  mutations
});
//导出store对象
export default store;